<template>
  <div class="about-master-container" v-if="routerAlive">
    <base-breadcrumb :breadcrumb="!isAudit">
      <b-steps :current="stepVal" direction="vertical" @change.self="stepChange">
        <b-step title="基本信息">
          <a-card v-show="activeKey[0]" slot="description" v-loading="loading" :bordered="false">
            <a-form-model ref="ruleForm" :model="formData" :rules="rules">
              <a-row>
                <a-col span="8">
                  <!-- 编辑时才显示-->
                  <a-form-model-item label="物资需求月计划编码">
                    <BaseInput v-model="formData.monthCode" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="项目名称" prop="projectCode">
                    <SelectDownProject v-model="formData.projectCode" :disabled="state === 3" @selectChange="
  formData.projectDeptId = $event.projectDeptId
                      formData.projectName = $event.projectName
formData.accountName = ''
                    " />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="编号" prop="code">
                    <BaseInputNumber :is-int="true" v-model="formData.code" v-if="state !== 3"
                      :max="99999999999999999999" />
                    <a-input v-model="formData.codeAll" disabled v-else />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="联系人" prop="accountName">
                    <a-input-search v-model="formData.accountName" placeholder="请选择" :disabled="state === 3"
                      @search="openPerson" @click="openPerson" />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="电话">
                    <BaseInput v-model="formData.phone" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="计划时间" prop="planTime">
                    <a-date-picker v-model="formData.planTime" value-format="YYYY-MM-DD" type="date"
                      :disabled="state === 3" />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建人">
                    <BaseInput v-model="formData.creatorName" disabled />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建时间">
                    <BaseInput v-model="formData.createTime" disabled />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
            <div v-if="!isAudit" class="pub-next-btn">
              <a-button v-if="state !== 3" :loading="loading" type="primary" @click="temporaryStorage(false)">
                保存草稿
              </a-button>
              <a-button :loading="loading" type="primary" @click="temporaryStorage(true)">
                下一步{{ $route.query.row }}
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="物资需用计划表">
          <a-card v-if="activeKey[1]" slot="description" :bordered="false">
            <detail ref="detail" :state="state" :row="row ? row : null" />
            <div v-if="!isAudit" class="pub-next-btn">
              <a-button type="primary" @click="prev">
                上一步
              </a-button>
              <a-button type="primary" @click="next">
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="相关附件">
          <a-card v-if="activeKey[2]" slot="description" :bordered="false">
            <u-table :upload-list="addFile" :delete-url="fileDel" :is-show="state !== 3" :list-url="fileList"
              :business-id="row.id" business-code="MM07" />
            <div v-if="!isAudit" class="pub-next-btn">
              <a-button type="primary" @click="prev">
                上一步
              </a-button>
            </div>
          </a-card>
        </b-step>
      </b-steps>
      <div v-if="!isAudit" class="pub-header-btn page-btn-right-top">
        <a-button v-if="state !== 3" :loading="loading" type="primary" @click="submit">
          提交
        </a-button>
        <a-button v-if="state === 3" type="primary" @click="openHistory">
          历史记录
        </a-button>
        <a-button v-checkVisibleInDetail @click="$close()">
          关闭
        </a-button>
      </div>
    </base-breadcrumb>
    <history :id="listId" ref="history" @close="closeHistoryModal"/>
    <person-list ref="personList" :org-id="formData.projectDeptId" @getPerson="getPerson" />
    <selectApprover :businessId="businessId" :processConfig="setProcessConfig"></selectApprover>
  </div>
</template>

<script>
import detail from './components/detail'
import history from './components/history'
import {
  monthPlanEditBasic,
  monthPlanAddBasic,
  audit,
  addFile,
  fileList,
  fileDel,
  projectList,
  monthPlanBasicDetail
} from '@/api/material/materialMasterPlan/monthPlan'
import SelectDownProject from '@/components/Select/SelectDownProject'

export default {
  name: 'a' + Date.now(),
  components: {
    detail,
    history,
    SelectDownProject
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      listId: '',
      routerAlive: true,
      activeKey: [true, false, false, false, false, false, false],
      loading: false,
      state: Number(this.$route.query.state),
      isSubmit: false,
      row: this.$route.query.row,
      formData: {
        projectDeptId: '',
        createTime: this.getNowTime(),
        monthCode: null,
        projectName: '',
        projectCode: '',
        code: null,
        accountName: '',
        phone: '',
        planTime: '',
        creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name
      },
      optionArr: [],
      stepVal: 0,
      isNext: false,
      rules: {
        projectCode: { required: true, message: '项目名称不能为空', trigger: 'change' },
        code: { required: true, message: '编号不能为空', trigger: 'blur' },
        accountName: { required: true, message: '联系人不能为空', trigger: 'change' },
        planTime: { required: true, message: '计划时间不能为空', trigger: 'change' }
      },
      addFile: addFile(),
      fileDel: fileDel(),
      fileList: fileList(),
      projectArr: [],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.state = 3
        }
      }
    },
    stepVal(newVal, oldVal) {
      this.$set(this.activeKey, newVal, true)
    },
    $route(newVal, oldVal) {
      if (newVal.path === oldVal.path) {
        this.routerAlive = false;
        this.formData.id = this.$route.query.id;
        if (this.$route.query.pageTag === 'list'){
          this.listId = this.$route.query.id;
        }
        this.getEditInfo()
        this.$nextTick(() => {
          this.routerAlive = true
        })
      }
    }
  },
  mounted: async function () {
    if (this.state !== 1) {
      if (this.$route.query.pageTag === 'list') {
        this.listId = this.$route.query.id;
      }
      await this.getEditInfo()
      this.isSubmit = true
    }
    await this.getProjectList()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('mm_month_plan')
  },
  methods: {
    handleClose() {
      this.$close()
    },
    async getProjectList() {
      let res = await projectList()
      if (res.code === 200) {
        this.projectArr = res.data
      }
    },
    openPerson: function () {
      this.$refs.personList.open()
    },
    getPerson: function (row) {
      this.formData.accountName = row.name
      this.formData.phone = row.phoneNum
    },
    openHistory: function () {
      this.$refs.history.open()
    },
    next: function (val) {
      this.isNext = true
      this.stepVal++
    },
    prev() {
      this.isNext = true
      this.stepVal--
    },
    stepChange: function (val) {
      if (!this.row && !this.isAudit) {
        if (val) {
          this.$message.warning('切换步骤前请先填写基本信息')
          this.stepVal = 0
        }
      } else {
        if (!this.isNext) {
          this.$set(this.activeKey, val, !this.activeKey[val])
        }
      }
      this.isNext = false
    },
    // 获取编辑回显数据
    async getEditInfo() {
      const params = {
        id: this.$route.query.id || this.row.id
      }
      this.loading = true
      const res = await monthPlanBasicDetail(params)
      if (res.code === 200) {
        this.formData = this.row = res.data || {}
        this.formData.createTime = this.row.createTime
        this.formData.monthCode = this.row.monthCode
        this.formData.projectName = this.row.projectName
        this.formData.projectCode = this.row.projectCode
        this.formData.projectId = this.row.projectCode
        this.formData.code = this.row.code
        this.formData.accountName = this.row.accountName
        this.formData.phone = this.row.phone
        this.formData.planTime = this.row.planTime
        this.formData.createName = this.row.createName
      }
      this.loading = false
    },
    submit() {
      this.setProcessConfig = null;
      // this.save('approve');
      if (this.isSubmit) {
        this.submitApprovalConfirm(this.isSubmit ? this.processConfig : 6, async (flag) => {
          if (!flag) {
            this.loading = false
            return
          }
          this.loading = true
          audit({ baseId: this.row.id, auditStatus: this.row.auditStatus }).then(
            (res) => {
              this.$message.success('提交成功')
              this.loading = false
              //提交时，返回id
              this.businessId = this.formData.id || this.row.id;
              this.setProcessConfig = this.processConfig;
              //this.$multiTab.close(this.$route.fullpath)
              this.$close()
            },
            (error) => {
              this.$message.warning(error.data.message)
              this.loading = false
            }
          )
        })
      } else {
        this.$message.warning('提交之前请先暂存')
      }
    },
    closeHistoryModal(obj){
      this.formData.id = obj.id;
      this.state = obj.state;
      this.getEditInfo()
    },
    temporaryStorage(status) {
      if (this.state === 3) {
        return this.next()
      }
      this.$refs.ruleForm.validate(async (valid, object) => {
        if (valid) {
          this.loading = true
          if (this.state=== 2 || this.row) {
            this.formData.id = this.row.id
            if (this.formData.auditStatus !== 'DRAFT') {
              this.formData.auditStatus = 'CHANGE'
            }
            let res = await monthPlanEditBasic(this.formData)
            if (res.code === 200) {
              this.$message.success('暂存成功')
              this.isSubmit = true
              if (status) {
                this.next()
              }
            }
          } else {
            let res = await monthPlanAddBasic(this.formData)
            if (res.code === 200) {
              this.row = res.data
              this.$message.success('暂存成功')
              this.isSubmit = true
              this.getEditInfo()
              if (status) {
                this.next()
              }
            }
          }
          this.loading = false
        } else {
          return false
        }
      })
    }
  }
}
</script>
